import Cookies from "js-cookie";
import {getSiteInfo, getThemeColor, setSiteInfo, setThemeColor, getSiteGroup, setSiteGroup, getCurrentSite, setCurrentSite} from "@/utils/storage";
import {getSiteInit} from "@/api/setting";
import { getWebStation } from "@/api/site";
const state = {
    // 侧边栏控制
    sidebar: {
        opened: Cookies.get('sidebarStatus') ? !!+Cookies.get('sidebarStatus') : true,
    },
    site_info: getSiteInfo(),
    site_group: getSiteGroup() ? getSiteGroup() : [],
    // 当前站点
    current_site: getCurrentSite() ? getCurrentSite() : 1,
    theme_color: getThemeColor() ? getThemeColor() : '#4D99F2',
    baseUrl: process.env.NODE_ENV === 'development' ? process.env.VUE_APP_RUN_BASE_URL : window.location.origin + '/hcs/#'
}

const mutations = {
    // 切换sideBar是否展开
    TOGGLE_SIDEBAR: state => {
        state.sidebar.opened = !state.sidebar.opened
        if (state.sidebar.opened) {
            Cookies.set('sidebarStatus', 1)
        } else {
            Cookies.set('sidebarStatus', 0)
        }
    },
    // 设置站点信息并更新
    SET_SITE_INFO: (state, siteInfo) => {
        setSiteInfo(siteInfo)
        state.site_info = siteInfo
    },
    // 直接关闭Sidebar
    CLOSE_SIDEBAR: state => {
        state.sidebar.opened = true;
        Cookies.set('sidebarStatus', 1)
    },
    // 设置主题颜色
    SET_THEME_COLOR: (state, themeColor) => {
        setThemeColor(themeColor)
        state.theme_color = themeColor
    },
    // 设置站群
    SET_SITE_GROUP: (state, sites) => {
      setSiteGroup(sites)
      state.site_group = sites
    },
    // 设置站点
    SET_CURRENT_SITE: (state, site) => {
      setCurrentSite(site)
      state.current_site = site
    },
}

const actions = {
    toggleSideBar({commit}) {
        commit('TOGGLE_SIDEBAR')
    },
    setSiteInfo({ commit }) {
        return new Promise((resolve, reject) => {
            getSiteInit().then(res => {
                if(res.data) {
                    if(process.env.NODE_ENV === 'development') console.log(res.data)
                    commit('SET_SITE_INFO',res.data)
                    resolve(res)
                }
            }).catch(error => {
                reject(error)
            })
        })
    },
    setSiteGroup({ commit }) {
      return new Promise((resolve, reject) => {
        getWebStation().then(res => {
              if(res.data) {
                  res.data = res.data.map(item=>{
                    return {
                      ...item,
                      title: item.name,
                      url: item.static_domain
                    }
                  })
                  if(process.env.NODE_ENV === 'development') console.log(res.data)
                  commit('SET_SITE_GROUP',res.data)
                  resolve(res)
              }
          }).catch(error => {
              reject(error)
          })
      })
    }
}

export default {
    namespaced: true, //命名空间
    state,
    mutations,
    actions,
}
